package org.yinweichen.llm_dataset_backend.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.yinweichen.llm_dataset_backend.entity.OriginalQuestion;
import org.yinweichen.llm_dataset_backend.entity.OriginalQuestionId;

import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.data.domain.Pageable;

public interface OriginalQuestionRepository extends JpaRepository<OriginalQuestion, OriginalQuestionId> {
    List<OriginalQuestion> findAllById(Long id);

    @Modifying
    @Query("UPDATE OriginalQuestion q SET q.active = false WHERE q.id = :id AND q.version = :version")
    void inactivate(@Param("id") Long id, @Param("version") String version);

    @Modifying
    @Query("UPDATE OriginalQuestion q SET q.active = true WHERE q.id = :id AND q.version = :version")
    void activate(@Param("id") Long id, @Param("version") String version);

    @Modifying
    @Query("DELETE FROM OriginalQuestion q WHERE q.version = :version AND q.active = false")
    void hardDelete(@Param("version") String version);

    @Query("SELECT q FROM OriginalQuestion q WHERE q.title LIKE %:keyword%")
    List<OriginalQuestion> findByTitleLike(@Param("keyword") String keyword);

    @Query("SELECT q FROM OriginalQuestion q WHERE q.title LIKE %:keyword% AND q.version = :version")
    List<OriginalQuestion> findByTitleLikeAndVersion(@Param("keyword") String keyword, @Param("version") String version);

    @Query("SELECT q FROM OriginalQuestion q WHERE q.id = :id")
    List<OriginalQuestion> findById(@Param("id") Long id);

    @Query("SELECT q FROM OriginalQuestion q WHERE q.id = :id AND q.version = :version")
    Optional<OriginalQuestion> findByIdAndVersion(@Param("id") Long id, @Param("version") String version);

    boolean existsById(Long id);

    @Query("SELECT q FROM OriginalQuestion q WHERE q.version = :version")
    List<OriginalQuestion> findAllByVersion(@Param("version") String version, Pageable pageable);

    @Query("SELECT q FROM OriginalQuestion q WHERE q.version = :version")
    List<OriginalQuestion> findAllByVersion(@Param("version") String version);
    /**
     * 根据关键词统计匹配的问题数量
     * @param keyword 搜索关键词
     * @return 匹配的问题数量
     */
    @Query("SELECT COUNT(q) FROM OriginalQuestion q WHERE q.title LIKE %:keyword% AND q.version = :version")
    long countByTitleLikeAndVersion(@Param("keyword") String keyword, @Param("version") String version);

    @Query("SELECT COUNT(q) FROM OriginalQuestion q WHERE q.version = :version")
    long countByVersion(@Param("version") String version);
}
